-- 用户战斗实体（一般是自己或宠物）
local Entity = require("gameLogic.fightEntity.Entity")
local UserEntity = class("UserEntity", Entity)
local FightConst = require("const.FightConst")

function UserEntity:ctor(manager)
    UserEntity.super.ctor(self, manager)
    self._autoDelay = FightConst.USER_AUTO_DELAY
    self._active = false
    self._lock = false
end

function UserEntity:start()
    UserEntity.super.start(self)
    self._sugnalUserClickSkill =
        G_SignalManager:add(SignalConst.EVENT_USER_SKILL_CLICK, handler(self, self._onEventClickSkill))
end

function UserEntity:_tick()
    if self._lock then
        return
    end
    if not self._active then
        self._active = true
        G_SignalManager:dispatch(SignalConst.EVENT_USER_ACTIVE_UI, self._autoDelay)
    end
    if self._autoDelay > 0 then
        self._autoDelay = self._autoDelay - G_Time.deltaTime
    else
        self:autoAttack()
        G_SignalManager:dispatch(SignalConst.EVENT_USER_CLOSE_UI)
    end
end

function UserEntity:reset()
    UserEntity.super.reset(self)
    self._active = false
    self._lock = false
    self._autoDelay = FightConst.USER_AUTO_DELAY
end

function UserEntity:onDestroy()
    UserEntity.super.onDestroy(self)
    printDebug("AutoEntity:onDestroy")
    self._sugnalUserClickSkill:remove()
    self._sugnalUserClickSkill = nil
end

function UserEntity:_onEventClickSkill(id, index, skillId)
    local skill = self:_getSkillById(skillId)
    printDebug("UserEntity:_onEventClickSkill index=" .. index .. " skillId=" .. skillId)
    G_SignalManager:dispatch(SignalConst.EVENT_USER_CLOSE_UI)
    if skill then
        self._lock = true
        skill:attack(index)
    else
        self:setDone(true)
    end
end

function UserEntity:_getSkillById(id)
    for i = 1, #self._skillList do
        if self._skillList[i]:getId() == id then
            return self._skillList[i]
        end
    end
end

function UserEntity:autoAttack()
    local manager = self:getManager()
    local targets = manager:getEnemyEntitys(self:getStanding())
    if #targets == 0 then
        self:setDone(true)
        return
    end
    self._lock = true
    local index = math.random(1, #self._skillList)
    local targetIndex = math.random(1, #targets)
    self._skillList[index]:attack(targetIndex)
end

function UserEntity:_updateBlood()
    UserEntity.super._updateBlood(self)
    local AttributeConst = require("const.AttributeConst")
    local blood = self._attr:getAttrValue(AttributeConst.BLOOD)
    local initBlood = self._attr:getAttrValue(AttributeConst.INIT_BLOOD)
    G_SignalManager:dispatch(SignalConst.EVENT_USER_BLOOD_UPDATE, blood / initBlood)
end

return UserEntity
